part of 'page.dart';

class _CollectionSelectionPageView extends StatelessWidget with ScreenUtilMixin {
  const _CollectionSelectionPageView({
    required _CollectionSelectionPageWloc wloc,
  }) : _wloc = wloc;

  static const _dragIconHeight = 40.0;
  static const _tileTrailingMinWidth = 80.0;

  final _CollectionSelectionPageWloc _wloc;

  Widget? _buildNavigationBarLeading({
    required _CollectionSelectionPageWlocState state,
    required BuildContext context,
  }) {
    if (state is _DefaultState) {
      const kReorderIconSize = 27.0;

      final width = kReorderIconSize * kMaterialIconRatio +
          kVisibleNavigationBarHorizontalIconPadding * 2 * logWidthScaleFactor;

      return AppIconButton(
        icon: Icon(
          Icons.reorder_rounded,
          size: kReorderIconSize,
          color: CoreTheme.of(context).primaryColor,
        ),
        height: double.infinity,
        width: width,
        onPressed: _wloc.onCollectionListItemReorderingIconPressed,
      );
    }

    if (state is _CollectionListItemReordering) {
      return ScaledNavigationBarTextButton(
        text: CoreTranslation.of(context).navigationBarCancelButtonTitle,
        navigationButtonAutoSizeGroup:
            _wloc.navigationButtonAutoSizeGroups[_CollectionListItemReordering],
        onPressed: _wloc.onCollectionListItemReorderingCancellationButtonPressed,
      );
    }

    if (state is _CollectionCreation) {
      return ScaledNavigationBarTextButton(
        text: CoreTranslation.of(context).navigationBarCancelButtonTitle,
        navigationButtonAutoSizeGroup: _wloc.navigationButtonAutoSizeGroups[_CollectionCreation],
        onPressed: _wloc.onCollectionCreationCancellationButtonPressed,
      );
    }

    if (state is _CollectionFolderCreation) {
      return ScaledNavigationBarTextButton(
        text: CoreTranslation.of(context).navigationBarCancelButtonTitle,
        navigationButtonAutoSizeGroup:
            _wloc.navigationButtonAutoSizeGroups[_CollectionFolderCreation],
        onPressed: _wloc.onCollectionFolderCreationCancellationButtonPressed,
      );
    }
    return null;
  }

  Widget? _buildNavigationBarTrailing({
    required _CollectionSelectionPageWlocState state,
    required BuildContext context,
  }) {
    if (state is _DefaultState) {
      const searchIconSize = 22.5;
      const addIconSize = 24.0;
      var visibleIconsGap = 24 * logWidthScaleFactor;
      const searchIconRatio = kSemiboldIconRatio;
      const addIconRatio = kSemiboldIconRatio;

      visibleIconsGap = max(
        visibleIconsGap,
        searchIconSize * 0.5 * (1 - searchIconRatio) + addIconSize * 0.5 * (1 - addIconRatio),
      );

      final searchButtonWidth = visibleIconsGap + searchIconRatio * searchIconSize;

      final addButtonWidth = visibleIconsGap * 0.5 +
          addIconRatio * addIconSize +
          kVisibleNavigationBarHorizontalIconPadding * logWidthScaleFactor;

      final addIconRightMargin = addButtonWidth - addIconRatio * addIconSize - visibleIconsGap;

      return Row(
        mainAxisSize: MainAxisSize.min,
        children: [
          AppIconButton(
            icon: Icon(
              CustomSemiboldIcons.search,
              color: CoreTheme.of(context).primaryColor,
              size: searchIconSize,
            ),
            height: double.infinity,
            width: searchButtonWidth,
            onPressed: _wloc.onSearchIconButtonPressed,
          ),
          AppIconButton(
            icon: Icon(
              CustomSemiboldIcons.plus,
              size: addIconSize,
              color: CoreTheme.of(context).primaryColor,
            ),
            height: double.infinity,
            width: addButtonWidth,
            iconPadding: EdgeInsets.only(
              right: addIconRightMargin > 0 ? addIconRightMargin : 0,
              left: addIconRightMargin < 0 ? -addIconRightMargin : 0,
            ),
            onPressed: _wloc.onCollectionListItemCreationIconPressed,
          ),
        ],
      );
    }

    if (state is _CollectionListItemReordering) {
      return ScaledNavigationBarTextButton(
        text: CoreTranslation.of(context).navigationBarDoneButtonTitle,
        isDefault: true,
        navigationButtonAutoSizeGroup:
            _wloc.navigationButtonAutoSizeGroups[_CollectionListItemReordering],
        onPressed: _wloc.onCollectionListItemReorderingCompletionButtonPressed,
      );
    }

    if (state is _CollectionCreation) {
      return ScaledNavigationBarTextButton(
        text: CoreTranslation.of(context).navigationBarCreateButtonTitle,
        isDefault: true,
        navigationButtonAutoSizeGroup: _wloc.navigationButtonAutoSizeGroups[_CollectionCreation],
        onPressed: _wloc.onCollectionCreationCompletionButtonPressed,
      );
    }

    if (state is _CollectionFolderCreation) {
      return ScaledNavigationBarTextButton(
        text: CoreTranslation.of(context).navigationBarCreateButtonTitle,
        isDefault: true,
        navigationButtonAutoSizeGroup:
            _wloc.navigationButtonAutoSizeGroups[_CollectionFolderCreation],
        onPressed: _wloc.onCollectionFolderCreationCompletionButtonPressed,
      );
    }
    return null;
  }

  Widget? _buildNavigationBarMiddle({
    required _CollectionSelectionPageWlocState state,
    required BuildContext context,
  }) {
    late String title;

    if (state is _DefaultState) {
      title = CollectionSelectionPageTranslation.of(context).title;
    } else if (state is _CollectionListItemReordering) {
      title = CollectionSelectionPageTranslation.of(context).title;
    } else if (state is _CollectionCreation) {
      title = CollectionCoreTranslation.of(context).collectionTitleEnteringInstruction;
    } else if (state is _CollectionFolderCreation) {
      title = CollectionCoreTranslation.of(context).collectionFolderTitleEnteringInstruction;
    }

    return NavigationBarTitle(
      title: title,
    );
  }

  Widget _buildColectionListItemTileDivider() {
    return const TileSeparator();
  }

  Widget _buildContent({
    required _CollectionSelectionPageWlocState state,
    required BuildContext context,
  }) {
    if (state is _DefaultState) {
      return _buildDefaultContent(
        state: state,
        context: context,
      );
    }
    if (state is _CollectionListItemReordering) {
      return _buildCollectionListItemReorderingContent(
        state: state,
        context: context,
      );
    }
    if (state is _CollectionCreation) {
      return _buildCollectionCreationContent(
        state: state,
        context: context,
      );
    }
    if (state is _CollectionFolderCreation) {
      return _buildCollectionFolderCreationContent(
        state: state,
        context: context,
      );
    }

    throw Exception();
  }

  Widget _buildCollectionListItemReorderingContent({
    required _CollectionListItemReordering state,
    required BuildContext context,
  }) {
    return Scrollbar(
      child: ReorderableList(
        onReorder: _wloc.onReorderCollectionListItems,
        decoratePlaceholder: (widget, decorationOpacity) {
          return DecoratedPlaceholder(
            offset: 0,
            widget: widget,
          );
        },
        child: ExtendedListView(
          padding: EdgeInsets.zero,
          itemCount: state.reorderedCollectionListItemModels.length,
          headerBuilder: (context) {
            return const TileGap();
          },
          itemBuilder: (context, index) {
            return ReorderableItem(
              key: _wloc.getReorderableCollectionListItemModelKey(
                  state.reorderedCollectionListItemModels[index]),
              childBuilder: (context, reorderableItemState) {
                final shouldBeTransparent =
                    reorderableItemState == ReorderableItemState.placeholder;

                return PageTileHorizontalPadding(
                  child: Visibility(
                    visible: !shouldBeTransparent,
                    maintainSize: true,
                    maintainAnimation: true,
                    maintainState: true,
                    child: _buildCollectionListItemTile(
                      collectionListItemModel: state.reorderedCollectionListItemModels[index],
                      state: state,
                      context: context,
                    ),
                  ),
                );
              },
            );
          },
          dividerBuilder: (context, index) {
            return _buildColectionListItemTileDivider();
          },
          footerBuilder: (context) {
            return const TileGap();
          },
        ),
      ),
    );
  }

  Widget _buildDefaultContent({
    required _DefaultState state,
    required BuildContext context,
  }) {
    return Scrollbar(
      child: PageTileHorizontalPadding(
        child: ExtendedListView(
          padding: EdgeInsets.zero,
          headerBuilder: (context) {
            return const TileGap();
          },
          itemCount: state.collectionListItemModels.length,
          itemBuilder: (context, index) {
            return _buildCollectionListItemTile(
              collectionListItemModel: state.collectionListItemModels[index],
              state: state,
              context: context,
            );
          },
          dividerBuilder: (context, index) {
            return _buildColectionListItemTileDivider();
          },
          footerBuilder: (context) {
            return const TileGap();
          },
        ),
      ),
    );
  }

  Widget _buildCollectionCreationContent({
    required _CollectionCreation state,
    required BuildContext context,
  }) {
    return Column(
      children: [
        Expanded(
          child: Scrollbar(
            child: PageTileHorizontalPadding(
              child: ExtendedListView(
                padding: EdgeInsets.zero,
                headerBuilder: (context) {
                  return const TileGap();
                },
                itemCount: state.collectionListItemModels.length,
                itemBuilder: (context, index) {
                  return _buildCollectionListItemTile(
                    collectionListItemModel: state.collectionListItemModels[index],
                    state: state,
                    context: context,
                  );
                },
                dividerBuilder: (context, index) {
                  return _buildColectionListItemTileDivider();
                },
                footerBuilder: (context) {
                  return const TileGap();
                },
              ),
            ),
          ),
        ),
        CollectionListItemKeyboardTextField(
          controller: _wloc.textEditingController,
          focusNode: _wloc.textFieldFocusNode,
          placeholder: CollectionCoreTranslation.of(context).collectionTitleTextFieldPlaceholder,
          onSubmitted: _wloc.onCollectionCreationCompletionButtonPressed,
          shakeAnimationController: _wloc.shakeAnimationController,
        ),
        PlatformKeyboardPlaceholder(
          backgroundColor: CollectionCoreTheme.of(context).collectionListItemKeyboardTextFieldColor,
          tabBarHeight: kTabBarHeight + ScreenUtil().bottomBarHeight,
        ),
      ],
    );
  }

  Widget _buildCollectionFolderCreationContent({
    required _CollectionFolderCreation state,
    required BuildContext context,
  }) {
    return Column(
      children: [
        Expanded(
          child: Scrollbar(
            child: PageTileHorizontalPadding(
              child: ExtendedListView(
                padding: EdgeInsets.zero,
                headerBuilder: (context) {
                  return const TileGap();
                },
                itemCount: state.collectionListItemModels.length,
                itemBuilder: (context, index) {
                  return _buildCollectionListItemTile(
                    collectionListItemModel: state.collectionListItemModels[index],
                    state: state,
                    context: context,
                  );
                },
                dividerBuilder: (context, index) {
                  return _buildColectionListItemTileDivider();
                },
                footerBuilder: (context) {
                  return const TileGap();
                },
              ),
            ),
          ),
        ),
        CollectionListItemKeyboardTextField(
          controller: _wloc.textEditingController,
          focusNode: _wloc.textFieldFocusNode,
          placeholder:
              CollectionCoreTranslation.of(context).collectionFolderTitleTextFieldPlaceholder,
          onSubmitted: _wloc.onCollectionFolderCreationCompletionButtonPressed,
          shakeAnimationController: _wloc.shakeAnimationController,
        ),
        PlatformKeyboardPlaceholder(
          backgroundColor: CollectionCoreTheme.of(context).collectionListItemKeyboardTextFieldColor,
          tabBarHeight: kTabBarHeight + ScreenUtil().bottomBarHeight,
        ),
      ],
    );
  }

  Widget _buildDragIcon({
    required BuildContext context,
  }) {
    return ReorderableListener(
      child: Container(
        color: Colors.transparent,
        width: 50,
        height: _dragIconHeight,
        child: Icon(
          CustomLightIcons.drag,
          size: 26,
          color: CollectionCoreTheme.of(context).dragIconColor,
        ),
      ),
    );
  }

  Widget? _buildCollectionFolderTileTrailing({
    required _CollectionSelectionPageWlocState state,
    required BuildContext context,
  }) {
    if (state is _CollectionListItemReordering) {
      return ConstrainedBox(
        constraints: const BoxConstraints(
          minWidth: _tileTrailingMinWidth,
        ),
        child: Align(
          alignment: Alignment.centerRight,
          child: _buildDragIcon(
            context: context,
          ),
        ),
      );
    }
    return null;
  }

  Widget _buildCollectionFolderTile({
    required _CollectionFolderModel collectionFolderModel,
    required _CollectionSelectionPageWlocState state,
    required BuildContext context,
  }) {
    final trailing = _buildCollectionFolderTileTrailing(
      state: state,
      context: context,
    );

    VoidCallback? onPressed;
    if (state is _DefaultState && collectionFolderModel.isCustom) {
      onPressed = () {
        _wloc.onCustomCollectionFolderTilePressed(
          customCollectionFolderId: collectionFolderModel.id,
        );
      };
    }

    final collectionTiles = collectionFolderModel.collectionModels.map((collectionModel) {
      return _buildCollectionTile(
        collectionModel: collectionModel,
        nested: true,
        state: state,
        context: context,
      );
    }).toList();

    return RoundedTileGroup(
      tiles: [
        _CollectionFolderTile(
          title: collectionFolderModel.title,
          trailing: trailing,
          onPressed: onPressed,
          showPremiumBadge: !collectionFolderModel.permitted,
        ),
        ...collectionTiles,
      ],
    );
  }

  Widget _buildCollectionTileTrailing({
    required _CollectionModel collectionModel,
    required bool nested,
    required _CollectionSelectionPageWlocState state,
    required BuildContext context,
  }) {
    late Widget trailing;

    if (state is _CollectionListItemReordering) {
      if (nested) {
        trailing = const SizedBox(
          width: _tileTrailingMinWidth,
        );
      } else {
        trailing = _buildDragIcon(
          context: context,
        );
      }
    } else {
      trailing = Row(
        mainAxisSize: MainAxisSize.min,
        children: [
          Text(
            '${collectionModel.progressPercent}',
            style: CollectionSelectionPageTheme.of(context).textTheme.collectionProgressPercent,
          ),
          Container(width: 1),
          Text(
            '%',
            style: CollectionSelectionPageTheme.of(context).textTheme.collectionProgressPercent,
          ),
          AppCheckbox(
            value: collectionModel.selectionEffective,
            onChanged: (selected) {
              _wloc.onCollectionCheckboxPressed(
                collectionModel: collectionModel,
              );
            },
            materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
          ),
        ],
      );
    }

    return ConstrainedBox(
      constraints: const BoxConstraints(
        minWidth: _tileTrailingMinWidth,
      ),
      child: Align(
        alignment: Alignment.centerRight,
        child: trailing,
      ),
    );
  }

  Widget _buildCollectionTile({
    required _CollectionModel collectionModel,
    required bool nested,
    required _CollectionSelectionPageWlocState state,
    required BuildContext context,
  }) {
    final trailing = _buildCollectionTileTrailing(
      collectionModel: collectionModel,
      nested: nested,
      state: state,
      context: context,
    );

    VoidCallback? onPressed;
    if (state is _DefaultState) {
      onPressed = () {
        _wloc.onCollectionTilePressed(
          collectionId: collectionModel.id,
        );
      };
    }

    final tile = _CollectionTile(
      title: collectionModel.title,
      trailing: trailing,
      onPressed: onPressed,
      showPremiumBadge: !collectionModel.permitted,
    );

    if (nested) {
      return tile;
    } else {
      return RoundedTileGroup(
        tiles: [
          tile,
        ],
      );
    }
  }

  Widget _buildCollectionListItemTile({
    required _CollectionListItemModel collectionListItemModel,
    required _CollectionSelectionPageWlocState state,
    required BuildContext context,
  }) {
    if (collectionListItemModel is _CollectionModel) {
      final collectionModel = collectionListItemModel;

      return _buildCollectionTile(
        collectionModel: collectionModel,
        nested: false,
        state: state,
        context: context,
      );
    }
    if (collectionListItemModel is _CollectionFolderModel) {
      final collectionFolderModel = collectionListItemModel;

      return _buildCollectionFolderTile(
        collectionFolderModel: collectionFolderModel,
        state: state,
        context: context,
      );
    }
    throw Exception();
  }

  @override
  Widget build(BuildContext context) {
    return WlocBuilder<_CollectionSelectionPageWloc, _CollectionSelectionPageWlocState>(
      wloc: _wloc,
      builder: (context, state) {
        return CupertinoPageScaffold(
          resizeToAvoidBottomInset: false,
          backgroundColor: CoreTheme.of(context).backgroundColor,
          navigationBar: CupertinoNavigationBar(
            automaticallyImplyLeading: false,
            automaticallyImplyMiddle: false,
            padding: EdgeInsetsDirectional.zero,
            backgroundColor: CoreTheme.of(context).navigationBarColor,
            brightness: CoreTheme.of(context).brightness,
            leading: _buildNavigationBarLeading(
              state: state,
              context: context,
            ),
            trailing: _buildNavigationBarTrailing(
              state: state,
              context: context,
            ),
            middle: _buildNavigationBarMiddle(
              state: state,
              context: context,
            ),
          ),
          child: SizedBox.expand(
            child: _buildContent(
              state: state,
              context: context,
            ),
          ),
        );
      },
    );
  }
}
